import React, { useState, useEffect, useCallback } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from '@/components/ui/tabs';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from '@/components/ui/dialog';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import { Calendar as CalendarComponent } from '@/components/ui/calendar';
import { DateRange } from 'react-day-picker';
import {
  BarChart,
  Bar,
  LineChart,
  Line,
  AreaChart,
  Area,
  PieChart,
  Pie,
  Cell,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
  ScatterChart,
  Scatter
} from 'recharts';
import { toast } from 'sonner';
import {
  BarChart3,
  TrendingUp,
  TrendingDown,
  Users,
  MousePointer,
  Clock,
  Globe,
  Smartphone,
  Monitor,
  Tablet,
  Calendar,
  Download,
  Filter,
  RefreshCw,
  Eye,
  ArrowUpRight,
  ArrowDownRight,
  Activity,
  PieChart as PieChartIcon,
  LineChart as LineChartIcon,
  Settings,
  Share,
  FileText,
  Target,
  Zap,
  AlertTriangle,
  CheckCircle,
  Search,
  Pause,
  Play,
  X,
  Loader2
} from 'lucide-react';
import { format, subDays, startOfDay, endOfDay } from 'date-fns';
import { cn } from '@/lib/utils';

// 模拟数据
const userActivityData = [
  { name: '1月', users: 1200, sessions: 3400, pageViews: 8900 },
  { name: '2月', users: 1400, sessions: 4200, pageViews: 9800 },
  { name: '3月', users: 1100, sessions: 3800, pageViews: 8200 },
  { name: '4月', users: 1600, sessions: 4800, pageViews: 11200 },
  { name: '5月', users: 1800, sessions: 5200, pageViews: 12800 },
  { name: '6月', users: 2000, sessions: 5800, pageViews: 14200 }
];

const deviceData = [
  { name: '桌面端', value: 45, color: '#3B82F6' },
  { name: '移动端', value: 35, color: '#10B981' },
  { name: '平板端', value: 20, color: '#F59E0B' }
];

const pageViewsData = [
  { page: '控制台', views: 12500, bounce: 25, avgTime: '3:45' },
  { page: '智能聊天', views: 8900, bounce: 18, avgTime: '5:20' },
  { page: '版本发布', views: 6700, bounce: 32, avgTime: '2:15' },
  { page: '数据分析', views: 5400, bounce: 28, avgTime: '4:30' },
  { page: '用户管理', views: 4200, bounce: 35, avgTime: '2:50' }
];

// 实时用户活动数据（用于实时用户活动卡片）
const realTimeActivityData = [
  { page: '首页', location: '北京', users: 45 },
  { page: '产品页', location: '上海', users: 32 },
  { page: '关于我们', location: '广州', users: 28 },
  { page: '联系我们', location: '深圳', users: 19 },
  { page: '帮助中心', location: '杭州', users: 15 }
];

// 实时数据（用于图表）
const realTimeData = [
  { time: '14:00', users: 45 },
  { time: '14:05', users: 52 },
  { time: '14:10', users: 48 },
  { time: '14:15', users: 61 },
  { time: '14:20', users: 55 },
  { time: '14:25', users: 67 },
  { time: '14:30', users: 72 }
];

const keyMetrics = [
  {
    title: '总用户数',
    value: '24,847',
    change: '+12.5%',
    trend: 'up',
    icon: Users,
    color: 'text-blue-600'
  },
  {
    title: '活跃会话',
    value: '3,429',
    change: '+8.2%',
    trend: 'up',
    icon: MousePointer,
    color: 'text-green-600'
  },
  {
    title: '平均停留时间',
    value: '4:32',
    change: '+15.3%',
    trend: 'up',
    icon: Clock,
    color: 'text-purple-600'
  },
  {
    title: '跳出率',
    value: '28.5%',
    change: '-5.2%',
    trend: 'down',
    icon: TrendingDown,
    color: 'text-orange-600'
  }
];

// 数据类型定义
interface AnalyticsData {
  userActivity: UserActivityData[];
  deviceStats: DeviceData[];
  pageViews: PageViewData[];
  realTimeUsers: RealTimeData[];
  realTimeData: {
    activeUsers: number;
    pageViews: number;
    sessions: number;
    data: Array<{
      time: string;
      users: number;
      pageViews: number;
    }>;
  };
  keyMetrics: KeyMetric[];
  alerts: AlertData[];
  heatmapData?: Array<{
    hour: number;
    day: number;
    value: number;
    count: number;
  }>;
}

interface UserActivityData {
  date: string;
  users: number;
  sessions: number;
  pageViews: number;
  bounceRate: number;
}

interface DeviceData {
  name: string;
  value: number;
  percentage: number;
  color: string;
}

interface PageViewData {
  page: string;
  views: number;
  uniqueViews: number;
  avgTime: number;
  bounceRate: number;
}

interface RealTimeData {
  timestamp: string;
  activeUsers: number;
  pageViews: number;
  events: number;
}

interface KeyMetric {
  id: string;
  name: string;
  value: number;
  unit: string;
  change: number;
  changeType: 'increase' | 'decrease';
  target?: number;
  status: 'normal' | 'warning' | 'critical';
}

interface AlertData {
  id: string;
  type: 'warning' | 'error' | 'info';
  message: string;
  timestamp: string;
  resolved: boolean;
}

interface AnalyticsReport {
  id: string;
  name: string;
  description: string;
  type: 'user' | 'performance' | 'business' | 'custom';
  status: 'generating' | 'completed' | 'failed';
  createdAt: string;
  data?: any;
}

interface CustomMetric {
  id: string;
  name: string;
  value: number;
  unit: string;
  change: number;
  target?: number;
  formula?: string;
  dataSource?: string;
}

interface DateRangeOption {
  label: string;
  value: string;
  getDates: () => { from: Date; to: Date };
}

interface ExportOptions {
  format: 'excel' | 'pdf' | 'csv';
  includeCharts: boolean;
  dateRange: DateRange | undefined;
}

export default function AnalyticsPage() {
  // 基础状态
  const [timeRange, setTimeRange] = useState('7d');
  const [selectedMetric, setSelectedMetric] = useState('users');
  const [activeTab, setActiveTab] = useState('overview');
  const [loading, setLoading] = useState(false);
  const [refreshing, setRefreshing] = useState(false);
  const [error, setError] = useState<string | null>(null);
  
  // 对话框状态
  const [showReportDialog, setShowReportDialog] = useState(false);
  const [showMetricDialog, setShowMetricDialog] = useState(false);
  const [showExportDialog, setShowExportDialog] = useState(false);
  const [showFilterDialog, setShowFilterDialog] = useState(false);
  
  // 日期范围状态
  const [dateRange, setDateRange] = useState<DateRange | undefined>({
    from: subDays(new Date(), 30),
    to: new Date(),
  });
  const [selectedDateRange, setSelectedDateRange] = useState('30d');
  
  // 筛选和搜索状态
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedMetrics, setSelectedMetrics] = useState<string[]>([]);
  const [chartType, setChartType] = useState<'line' | 'bar' | 'area'>('line');
  
  // 表单状态
  const [newReport, setNewReport] = useState({ name: '', description: '', type: 'user' });
  const [newMetric, setNewMetric] = useState({ name: '', value: 0, unit: '', target: 0, formula: '', dataSource: '' });
  
  const [exportOptions, setExportOptions] = useState<ExportOptions>({
    format: 'excel',
    includeCharts: true,
    dateRange: dateRange,
  });
  
  // 实时更新状态
  const [realTimeEnabled, setRealTimeEnabled] = useState(true);
  const [lastUpdated, setLastUpdated] = useState(new Date());
  
  // 分析数据状态
  const [analyticsData, setAnalyticsData] = useState<AnalyticsData | null>(null);
  
  // 模拟报告数据
  const [reports, setReports] = useState<AnalyticsReport[]>([
    {
      id: '1',
      name: '用户行为分析报告',
      description: '分析用户在平台上的行为模式和偏好',
      type: 'user',
      status: 'completed',
      createdAt: '2024-01-15 14:30',
    },
    {
      id: '2',
      name: '系统性能报告',
      description: '系统响应时间和资源使用情况分析',
      type: 'performance',
      status: 'generating',
      createdAt: '2024-01-15 16:20',
    },
    {
      id: '3',
      name: '业务增长分析',
      description: '业务指标和增长趋势分析',
      type: 'business',
      status: 'completed',
      createdAt: '2024-01-14 09:15',
    },
  ]);

  // 日期范围选项
  const dateRangeOptions: DateRangeOption[] = [
    {
      label: '今天',
      value: 'today',
      getDates: () => ({
        from: startOfDay(new Date()),
        to: endOfDay(new Date()),
      }),
    },
    {
      label: '昨天',
      value: 'yesterday',
      getDates: () => ({
        from: startOfDay(subDays(new Date(), 1)),
        to: endOfDay(subDays(new Date(), 1)),
      }),
    },
    {
      label: '过去7天',
      value: '7d',
      getDates: () => ({
        from: subDays(new Date(), 7),
        to: new Date(),
      }),
    },
    {
      label: '过去30天',
      value: '30d',
      getDates: () => ({
        from: subDays(new Date(), 30),
        to: new Date(),
      }),
    },
    {
      label: '过去90天',
      value: '90d',
      getDates: () => ({
        from: subDays(new Date(), 90),
        to: new Date(),
      }),
    },
  ];

  // 数据获取函数
  const fetchAnalyticsData = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 生成模拟数据
      const days = dateRange ? Math.ceil((dateRange.to!.getTime() - dateRange.from!.getTime()) / (1000 * 60 * 60 * 24)) : 30;
      
      const userActivity: UserActivityData[] = Array.from({ length: days }, (_, i) => {
        const date = subDays(dateRange?.to || new Date(), days - i - 1);
        return {
          date: format(date, 'yyyy-MM-dd'),
          users: Math.floor(Math.random() * 1000) + 500,
          sessions: Math.floor(Math.random() * 1500) + 800,
          pageViews: Math.floor(Math.random() * 5000) + 2000,
          bounceRate: Math.random() * 0.3 + 0.2,
        };
      });
      
      const deviceStats: DeviceData[] = [
        { name: '桌面端', value: 45, percentage: 45, color: '#8B5CF6' },
        { name: '移动端', value: 35, percentage: 35, color: '#10B981' },
        { name: '平板端', value: 20, percentage: 20, color: '#F59E0B' },
      ];
      
      const pageViews: PageViewData[] = [
        { page: '/dashboard', views: 12500, uniqueViews: 8900, avgTime: 245, bounceRate: 0.25 },
        { page: '/analytics', views: 8900, uniqueViews: 6200, avgTime: 320, bounceRate: 0.18 },
        { page: '/users', views: 6700, uniqueViews: 4800, avgTime: 180, bounceRate: 0.35 },
        { page: '/settings', views: 4200, uniqueViews: 3100, avgTime: 150, bounceRate: 0.42 },
        { page: '/reports', views: 3800, uniqueViews: 2900, avgTime: 280, bounceRate: 0.22 },
      ];
      
      const realTimeUsers: RealTimeData[] = Array.from({ length: 24 }, (_, i) => ({
        timestamp: format(new Date(Date.now() - (23 - i) * 60 * 60 * 1000), 'HH:mm'),
        activeUsers: Math.floor(Math.random() * 200) + 50,
        pageViews: Math.floor(Math.random() * 500) + 100,
        events: Math.floor(Math.random() * 100) + 20,
      }));
      
      const keyMetrics: KeyMetric[] = [
        {
          id: '1',
          name: '总用户数',
          value: 12580,
          unit: '',
          change: 8.2,
          changeType: 'increase',
          status: 'normal',
        },
        {
          id: '2',
          name: '活跃用户',
          value: 8940,
          unit: '',
          change: 12.5,
          changeType: 'increase',
          status: 'normal',
        },
        {
          id: '3',
          name: '页面浏览量',
          value: 45680,
          unit: '',
          change: -2.1,
          changeType: 'decrease',
          status: 'warning',
        },
        {
          id: '4',
          name: '平均会话时长',
          value: 4.2,
          unit: '分钟',
          change: 15.8,
          changeType: 'increase',
          status: 'normal',
        },
      ];
      
      const alerts: AlertData[] = [
        {
          id: '1',
          type: 'warning',
          message: '页面加载时间超过预期阈值',
          timestamp: format(new Date(), 'yyyy-MM-dd HH:mm'),
          resolved: false,
        },
        {
          id: '2',
          type: 'info',
          message: '新用户注册量达到本月新高',
          timestamp: format(subDays(new Date(), 1), 'yyyy-MM-dd HH:mm'),
          resolved: true,
        },
      ];
      
      // 生成实时数据
      const realTimeDataObj = {
        activeUsers: Math.floor(Math.random() * 200) + 50,
        pageViews: Math.floor(Math.random() * 500) + 100,
        sessions: Math.floor(Math.random() * 150) + 30,
        data: Array.from({ length: 24 }, (_, i) => ({
          time: format(new Date(Date.now() - (23 - i) * 60 * 60 * 1000), 'HH:mm'),
          users: Math.floor(Math.random() * 200) + 50,
          pageViews: Math.floor(Math.random() * 500) + 100,
        })),
      };
      
      // 生成热力图数据
      const heatmapData = Array.from({ length: 168 }, (_, i) => ({
        hour: i % 24,
        day: Math.floor(i / 24),
        value: Math.random(),
        count: Math.floor(Math.random() * 1000),
      }));
      
      setAnalyticsData({
         userActivity,
         deviceStats,
         pageViews,
         realTimeUsers,
         realTimeData: realTimeDataObj,
         keyMetrics,
         alerts,
         heatmapData,
       });
      
      setLastUpdated(new Date());
    } catch (err) {
      setError('数据获取失败，请稍后重试');
      toast.error('数据获取失败');
    } finally {
      setLoading(false);
    }
  }, [dateRange]);
  
  // 自定义指标数据
  const [customMetrics, setCustomMetrics] = useState<CustomMetric[]>([
    {
      id: '1',
      name: '转化率',
      value: 3.2,
      unit: '%',
      change: 0.5,
      target: 5.0,
    },
    {
      id: '2',
      name: '平均响应时间',
      value: 245,
      unit: 'ms',
      change: -12,
      target: 200,
    },
    {
      id: '3',
      name: '用户满意度',
      value: 4.6,
      unit: '/5',
      change: 0.2,
      target: 4.8,
    },
  ]);

  /**
   * 获取设备图标
   */
  const getDeviceIcon = (device: string) => {
    switch (device) {
      case '桌面端':
        return <Monitor className="w-4 h-4" />;
      case '移动端':
        return <Smartphone className="w-4 h-4" />;
      case '平板端':
        return <Tablet className="w-4 h-4" />;
      default:
        return <Globe className="w-4 h-4" />;
    }
  };
  
  /**
   * 获取变化趋势图标
   */
  const getChangeIcon = (change: number) => {
    return change > 0 ? (
      <TrendingUp className="w-4 h-4 text-green-500" />
    ) : (
      <TrendingDown className="w-4 h-4 text-red-500" />
    );
  };
  
  /**
   * 获取报告类型标签
   */
  const getReportTypeBadge = (type: string) => {
    const typeConfig = {
      user: { label: '用户分析', className: 'bg-blue-100 text-blue-800' },
      performance: { label: '性能分析', className: 'bg-green-100 text-green-800' },
      business: { label: '业务分析', className: 'bg-purple-100 text-purple-800' },
      custom: { label: '自定义', className: 'bg-gray-100 text-gray-800' }
    };
    const config = typeConfig[type as keyof typeof typeConfig];
    return <Badge className={config.className}>{config.label}</Badge>;
  };
  
  /**
   * 获取状态标签
   */
  const getStatusBadge = (status: string) => {
    // 确保status存在且为字符串
    if (!status || typeof status !== 'string') {
      return <Badge className="bg-gray-100 text-gray-800">未知状态</Badge>;
    }
    
    const statusConfig = {
      ready: { label: '就绪', className: 'bg-blue-100 text-blue-800' },
      generating: { label: '生成中', className: 'bg-yellow-100 text-yellow-800' },
      failed: { label: '失败', className: 'bg-red-100 text-red-800' },
      completed: { label: '已完成', className: 'bg-green-100 text-green-800' },
      pending: { label: '待处理', className: 'bg-gray-100 text-gray-800' },
      processing: { label: '处理中', className: 'bg-blue-100 text-blue-800' },
      active: { label: '活跃', className: 'bg-green-100 text-green-800' },
      inactive: { label: '非活跃', className: 'bg-gray-100 text-gray-800' },
      error: { label: '错误', className: 'bg-red-100 text-red-800' },
      success: { label: '成功', className: 'bg-green-100 text-green-800' },
      warning: { label: '警告', className: 'bg-yellow-100 text-yellow-800' }
    };
    
    // 安全地获取配置，确保所有属性都存在
    const config = statusConfig[status as keyof typeof statusConfig];
    if (!config || typeof config !== 'object' || !config.className || !config.label) {
      return <Badge className="bg-gray-100 text-gray-800">未知状态</Badge>;
    }
    
    return <Badge className={config.className}>{config.label}</Badge>;
  };
  
  // 刷新数据
  const handleRefresh = useCallback(async () => {
    setRefreshing(true);
    await fetchAnalyticsData();
    setRefreshing(false);
    toast.success('数据已刷新');
  }, [fetchAnalyticsData]);

  // 处理日期范围变化
  const handleDateRangeChange = useCallback((value: string) => {
    setSelectedDateRange(value);
    if (value === 'custom') {
      // 自定义范围，不自动设置日期
      return;
    }
    const option = dateRangeOptions.find(opt => opt.value === value);
    if (option) {
      const dates = option.getDates();
      setDateRange(dates);
    }
  }, [dateRangeOptions]);

  // 导出数据
  const handleExport = useCallback(async (options: ExportOptions) => {
    setLoading(true);
    try {
      // 模拟导出过程
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      const filename = `analytics_${format(new Date(), 'yyyy-MM-dd')}.${options.format}`;
      
      // 这里应该调用实际的导出API
      console.log('导出数据:', {
        format: options.format,
        includeCharts: options.includeCharts,
        dateRange: options.dateRange,
        data: analyticsData || {},
      });
      
      toast.success(`数据已导出为 ${filename}`);
      setShowExportDialog(false);
    } catch (err) {
      toast.error('导出失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  }, [analyticsData]);

  // 生成报告
  const handleGenerateReport = useCallback(async () => {
    if (!newReport.name || !newReport.type) {
      toast.error('请填写完整的报告信息');
      return;
    }
    
    setLoading(true);
    try {
      // 模拟报告生成
      await new Promise(resolve => setTimeout(resolve, 3000));
      
      const report: AnalyticsReport = {
        id: Date.now().toString(),
        name: newReport.name,
        description: newReport.description,
        type: newReport.type as any,
        status: 'completed',
        createdAt: format(new Date(), 'yyyy-MM-dd HH:mm'),
        data: analyticsData || {},
      };
      
      setReports(prev => [report, ...prev]);
      setNewReport({ name: '', description: '', type: 'user' });
      setShowReportDialog(false);
      toast.success('报告生成成功');
    } catch (err) {
      toast.error('报告生成失败');
    } finally {
      setLoading(false);
    }
  }, [newReport, analyticsData]);

  // 添加自定义指标
  const handleAddMetric = useCallback(() => {
    if (!newMetric.name || !newMetric.unit) {
      toast.error('请填写完整的指标信息');
      return;
    }
    
    const metric: CustomMetric = {
      id: Date.now().toString(),
      name: newMetric.name,
      value: newMetric.value,
      unit: newMetric.unit,
      change: 0,
      target: newMetric.target || undefined,
      formula: newMetric.formula || undefined,
      dataSource: newMetric.dataSource || undefined,
    };
    
    setCustomMetrics(prev => [...prev, metric]);
    setNewMetric({ name: '', value: 0, unit: '', target: 0, formula: '', dataSource: '' });
    setShowMetricDialog(false);
    toast.success('自定义指标添加成功');
  }, [newMetric]);

  // 删除报告
  const handleDeleteReport = useCallback((reportId: string) => {
    setReports(prev => prev.filter(r => r.id !== reportId));
    toast.success('报告已删除');
  }, []);

  // 删除自定义指标
  const handleDeleteMetric = useCallback((metricId: string) => {
    setCustomMetrics(prev => prev.filter(m => m.id !== metricId));
    toast.success('指标已删除');
  }, []);

  // 获取状态图标
  const getStatusIcon = (status: string) => {
    switch (status) {
      case 'normal':
        return <CheckCircle className="w-4 h-4 text-green-500" />;
      case 'warning':
        return <AlertTriangle className="w-4 h-4 text-yellow-500" />;
      case 'critical':
        return <AlertTriangle className="w-4 h-4 text-red-500" />;
      default:
        return <CheckCircle className="w-4 h-4 text-gray-500" />;
    }
  };






  
  // 初始化数据
  useEffect(() => {
    fetchAnalyticsData();
  }, [fetchAnalyticsData]);

  // 监听日期范围变化
  useEffect(() => {
    if (dateRange?.from && dateRange?.to) {
      fetchAnalyticsData();
    }
  }, [dateRange, fetchAnalyticsData]);

  // 实时数据更新
  useEffect(() => {
    if (!realTimeEnabled) return;

    const interval = setInterval(async () => {
      try {
        // 模拟实时数据更新
        const newActiveUsers = Math.floor(Math.random() * 100) + 50;
        const newTime = format(new Date(), 'HH:mm:ss');
        
        setCustomMetrics(prev => prev.map(metric => ({
          ...metric,
          value: metric.value + (Math.random() - 0.5) * 2
        })));
        
        setLastUpdated(new Date());
      } catch (err) {
        console.error('实时数据更新失败:', err);
      }
    }, 30000); // 每30秒更新一次

    return () => clearInterval(interval);
  }, [realTimeEnabled]);

  return (
    <div className="space-y-6">
      {/* 页面头部 */}
      <div className="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4">
        <div>
          <h1 className="text-3xl font-bold tracking-tight">数据分析</h1>
          <p className="text-muted-foreground">
            深入了解用户行为和系统性能 • 最后更新: {lastUpdated ? format(lastUpdated, 'yyyy-MM-dd HH:mm:ss') : '未更新'}
          </p>
        </div>
        
        {/* 控制面板 */}
        <div className="flex flex-wrap gap-2">
          {/* 时间范围选择器 */}
          <Select value={selectedDateRange} onValueChange={handleDateRangeChange}>
            <SelectTrigger className="w-40">
              <Calendar className="w-4 h-4 mr-2" />
              <SelectValue placeholder="选择时间范围" />
            </SelectTrigger>
            <SelectContent>
              {dateRangeOptions.map(option => (
                <SelectItem key={option.value} value={option.value}>
                  {option.label}
                </SelectItem>
              ))}
            </SelectContent>
          </Select>
          
          {/* 自定义日期范围 */}
          {selectedDateRange === 'custom' && (
            <Popover>
              <PopoverTrigger asChild>
                <Button variant="outline" className="w-60">
                  <Calendar className="w-4 h-4 mr-2" />
                  {dateRange?.from ? (
                    dateRange.to ? (
                      `${format(dateRange.from, 'yyyy-MM-dd')} - ${format(dateRange.to, 'yyyy-MM-dd')}`
                    ) : (
                      format(dateRange.from, 'yyyy-MM-dd')
                    )
                  ) : (
                    '选择日期范围'
                  )}
                </Button>
              </PopoverTrigger>
              <PopoverContent className="w-auto p-0" align="start">
                <CalendarComponent
                  initialFocus
                  mode="range"
                  defaultMonth={dateRange?.from}
                  selected={dateRange}
                  onSelect={setDateRange}
                  numberOfMonths={2}
                />
              </PopoverContent>
            </Popover>
          )}
          
          {/* 实时更新开关 */}
          <Button
            variant={realTimeEnabled ? "default" : "outline"}
            onClick={() => setRealTimeEnabled(!realTimeEnabled)}
          >
            <Activity className="w-4 h-4 mr-2" />
            {realTimeEnabled ? '实时更新中' : '开启实时更新'}
          </Button>
          
          {/* 刷新按钮 */}
          <Button 
            variant="outline" 
            onClick={handleRefresh}
            disabled={refreshing}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${refreshing ? 'animate-spin' : ''}`} />
            刷新数据
          </Button>
          
          {/* 导出按钮 */}
          <Button onClick={() => setShowExportDialog(true)}>
            <Download className="w-4 h-4 mr-2" />
            导出数据
          </Button>
          
          {/* 筛选按钮 */}
          <Button variant="outline" onClick={() => setShowFilterDialog(true)}>
            <Filter className="w-4 h-4 mr-2" />
            筛选
          </Button>
        </div>
      </div>
      
      {/* 错误提示 */}
      {error && (
        <div className="bg-red-50 border border-red-200 rounded-lg p-4">
          <div className="flex items-center">
            <AlertTriangle className="w-5 h-5 text-red-500 mr-2" />
            <span className="text-red-700">{error}</span>
            <Button 
              variant="ghost" 
              size="sm" 
              onClick={() => setError(null)}
              className="ml-auto"
            >
              <X className="w-4 h-4" />
            </Button>
          </div>
        </div>
      )}

      {/* 标签页导航 */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="overview">概览</TabsTrigger>
          <TabsTrigger value="reports">报告管理</TabsTrigger>
          <TabsTrigger value="metrics">自定义指标</TabsTrigger>
          <TabsTrigger value="realtime">实时监控</TabsTrigger>
        </TabsList>

        {/* 概览标签页 */}
        <TabsContent value="overview" className="space-y-6">

          {/* 关键指标 */}
          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
            {(analyticsData?.keyMetrics || keyMetrics).map((metric, index) => (
              <Card key={index} className="hover:shadow-lg transition-shadow">
                <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                  <CardTitle className="text-sm font-medium">{metric.title || metric.name}</CardTitle>
                  {getStatusIcon(metric.status || 'normal')}
                </CardHeader>
                <CardContent>
                  <div className="text-2xl font-bold">
                    {typeof metric.value === 'number' ? metric.value.toLocaleString() : metric.value}
                  </div>
                  <div className="flex items-center text-xs text-muted-foreground">
                    {getChangeIcon(typeof metric.change === 'string' ? (metric.change.includes('+') ? 'increase' : 'decrease') : (metric.change > 0 ? 'increase' : 'decrease'))}
                    <span className={`ml-1 ${
                      (typeof metric.change === 'string' ? metric.change.includes('+') : metric.change > 0) ? 'text-green-600' : 
                      (typeof metric.change === 'string' ? metric.change.includes('-') : metric.change < 0) ? 'text-red-600' : 'text-gray-600'
                    }`}>
                      {typeof metric.change === 'string' ? metric.change : `${metric.change > 0 ? '+' : ''}${metric.change.toFixed(1)}%`}
                    </span>
                    <span className="ml-1">vs 上期</span>
                  </div>
                  {metric.target && (
                    <div className="mt-2 text-xs text-gray-400">
                      目标: {typeof metric.target === 'number' ? metric.target.toLocaleString() : metric.target}
                    </div>
                  )}
                </CardContent>
              </Card>
            )) || (
              // 加载状态
              Array.from({ length: 4 }).map((_, index) => (
                <Card key={index}>
                  <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
                    <div className="animate-pulse h-4 bg-gray-200 rounded w-3/4"></div>
                    <div className="animate-pulse h-4 w-4 bg-gray-200 rounded"></div>
                  </CardHeader>
                  <CardContent>
                    <div className="animate-pulse">
                      <div className="h-8 bg-gray-200 rounded w-1/2 mb-2"></div>
                      <div className="h-4 bg-gray-200 rounded w-1/4"></div>
                    </div>
                  </CardContent>
                </Card>
              ))
            )}
          </div>

          {/* 图表区域 */}
          <div className="grid gap-6 md:grid-cols-2">
            {/* 用户活动趋势 */}
            <Card>
              <CardHeader>
                <div className="flex items-center justify-between">
                  <div>
                    <CardTitle>用户活动趋势</CardTitle>
                    <CardDescription>
                      {dateRange?.from && dateRange?.to ? 
                        `${format(dateRange.from, 'yyyy-MM-dd')} 至 ${format(dateRange.to, 'yyyy-MM-dd')}` :
                        '过去7天的用户活跃度变化'
                      }
                    </CardDescription>
                  </div>
                  <Select value={chartType} onValueChange={setChartType}>
                    <SelectTrigger className="w-32">
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="line">折线图</SelectItem>
                      <SelectItem value="area">面积图</SelectItem>
                      <SelectItem value="bar">柱状图</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  {chartType === 'area' ? (
                    <AreaChart data={analyticsData?.userActivityData || []}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="date" />
                      <YAxis />
                      <Tooltip />
                      <Legend />
                      <Area
                        type="monotone"
                        dataKey="activeUsers"
                        stackId="1"
                        stroke="#8884d8"
                        fill="#8884d8"
                        fillOpacity={0.6}
                        name="活跃用户"
                      />
                      <Area
                        type="monotone"
                        dataKey="newUsers"
                        stackId="1"
                        stroke="#82ca9d"
                        fill="#82ca9d"
                        fillOpacity={0.6}
                        name="新用户"
                      />
                    </AreaChart>
                  ) : chartType === 'bar' ? (
                    <BarChart data={analyticsData?.userActivityData || []}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="date" />
                      <YAxis />
                      <Tooltip />
                      <Legend />
                      <Bar dataKey="activeUsers" fill="#8884d8" name="活跃用户" />
                      <Bar dataKey="newUsers" fill="#82ca9d" name="新用户" />
                    </BarChart>
                  ) : (
                    <LineChart data={analyticsData?.userActivityData || []}>
                      <CartesianGrid strokeDasharray="3 3" />
                      <XAxis dataKey="date" />
                      <YAxis />
                      <Tooltip />
                      <Legend />
                      <Line
                        type="monotone"
                        dataKey="activeUsers"
                        stroke="#8884d8"
                        strokeWidth={2}
                        name="活跃用户"
                      />
                      <Line
                        type="monotone"
                        dataKey="newUsers"
                        stroke="#82ca9d"
                        strokeWidth={2}
                        name="新用户"
                      />
                    </LineChart>
                  )}
                </ResponsiveContainer>
              </CardContent>
            </Card>

            {/* 设备分布 */}
            <Card>
              <CardHeader>
                <CardTitle>设备分布</CardTitle>
                <CardDescription>用户使用的设备类型统计</CardDescription>
              </CardHeader>
              <CardContent>
                <ResponsiveContainer width="100%" height={300}>
                  <PieChart>
                    <Pie
                      data={analyticsData?.deviceData || []}
                      cx="50%"
                      cy="50%"
                      labelLine={false}
                      label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                      outerRadius={80}
                      fill="#8884d8"
                      dataKey="value"
                    >
                      {(analyticsData?.deviceData || []).map((entry, index) => (
                        <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
                      ))}
                    </Pie>
                    <Tooltip />
                  </PieChart>
                </ResponsiveContainer>
              </CardContent>
            </Card>
          </div>

        <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
          {/* 页面访问统计 */}
          <Card>
            <CardHeader>
              <CardTitle className="text-lg font-semibold">页面访问统计</CardTitle>
              <CardDescription>各页面的访问量和用户行为数据</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {(analyticsData?.pageViewData || []).map((page, index) => (
                  <div key={index} className="flex items-center justify-between p-3 border rounded-lg hover:bg-gray-50 transition-colors">
                    <div className="flex-1">
                      <div className="flex items-center justify-between mb-2">
                        <h4 className="font-medium">{page.page}</h4>
                        <Badge variant="secondary">{page.views.toLocaleString()} 次访问</Badge>
                      </div>
                      <div className="flex items-center space-x-4 text-sm text-gray-600">
                        <span className="flex items-center space-x-1">
                          <TrendingDown className="w-3 h-3" />
                          <span>跳出率 {page.bounceRate}%</span>
                        </span>
                        <span className="flex items-center space-x-1">
                          <Clock className="w-3 h-3" />
                          <span>停留 {page.avgTime}</span>
                        </span>
                        <span className="flex items-center space-x-1">
                          <Users className="w-3 h-3" />
                          <span>独立访客 {page.uniqueVisitors}</span>
                        </span>
                      </div>
                      {/* 访问量趋势小图 */}
                      <div className="mt-2 h-8">
                        <ResponsiveContainer width="100%" height="100%">
                          <LineChart data={page.trend || []}>
                            <Line
                              type="monotone"
                              dataKey="value"
                              stroke="#8884d8"
                              strokeWidth={1}
                              dot={false}
                            />
                          </LineChart>
                        </ResponsiveContainer>
                      </div>
                    </div>
                  </div>
                )) || (
                  <div className="text-center py-8 text-gray-500">
                    <BarChart3 className="w-12 h-12 mx-auto mb-2 opacity-50" />
                    <p>暂无页面访问数据</p>
                  </div>
                )}
              </div>
            </CardContent>
          </Card>

          {/* 实时用户活动 */}
          <Card>
            <CardHeader>
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-lg font-semibold">实时用户活动</CardTitle>
                  <CardDescription>当前在线用户数量变化</CardDescription>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => setRealTimeEnabled(!realTimeEnabled)}
                >
                  {realTimeEnabled ? (
                    <Pause className="w-4 h-4 mr-1" />
                  ) : (
                    <Play className="w-4 h-4 mr-1" />
                  )}
                  {realTimeEnabled ? '暂停' : '开始'}
                </Button>
              </div>
            </CardHeader>
            <CardContent>
              <div className="mb-4">
                <div className="flex items-center space-x-2">
                  <div className={`w-3 h-3 rounded-full ${realTimeEnabled ? 'bg-green-500 animate-pulse' : 'bg-gray-400'}`}></div>
                  <span className="text-2xl font-bold text-gray-900">
                    {analyticsData?.realTimeData.activeUsers || 0}
                  </span>
                  <span className="text-sm text-gray-600">当前在线用户</span>
                </div>
                <div className="flex items-center space-x-4 mt-2 text-sm text-gray-500">
                  <span>页面浏览: {analyticsData?.realTimeData.pageViews || 0}</span>
                  <span>会话数: {analyticsData?.realTimeData.sessions || 0}</span>
                </div>
              </div>
              <ResponsiveContainer width="100%" height={200}>
                <LineChart data={analyticsData?.realTimeData.data || []}>
                  <CartesianGrid strokeDasharray="3 3" />
                  <XAxis dataKey="time" />
                  <YAxis />
                  <Tooltip />
                  <Line
                    type="monotone"
                    dataKey="users"
                    stroke="#3B82F6"
                    strokeWidth={2}
                    dot={{ fill: '#3B82F6', strokeWidth: 2, r: 4 }}
                    name="在线用户"
                  />
                  <Line
                    type="monotone"
                    dataKey="pageViews"
                    stroke="#10B981"
                    strokeWidth={2}
                    dot={{ fill: '#10B981', strokeWidth: 2, r: 4 }}
                    name="页面浏览"
                  />
                </LineChart>
              </ResponsiveContainer>
            </CardContent>
          </Card>
        </div>

        {/* 用户行为热力图 */}
        <Card>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-lg font-semibold">用户行为热力图</CardTitle>
                <CardDescription>用户在不同时间段的活跃度分布</CardDescription>
              </div>
              <div className="flex items-center space-x-2">
                <Select value={selectedMetrics[0] || 'activity'} onValueChange={(value) => setSelectedMetrics([value])}>
                  <SelectTrigger className="w-32">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="activity">用户活跃度</SelectItem>
                    <SelectItem value="pageViews">页面浏览</SelectItem>
                    <SelectItem value="sessions">会话数</SelectItem>
                    <SelectItem value="conversions">转化率</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-24 gap-1">
              {Array.from({ length: 24 }, (_, hour) => (
                <div key={hour} className="text-center">
                  <div className="text-xs text-gray-500 mb-1">{hour}</div>
                  {Array.from({ length: 7 }, (_, day) => {
                    // 使用真实数据或生成模拟数据
                    const heatmapCell = analyticsData?.heatmapData?.find(
                      cell => cell.hour === hour && cell.day === day
                    );
                    const intensity = heatmapCell?.value || Math.random();
                    const count = heatmapCell?.count || Math.floor(Math.random() * 1000);
                    
                    return (
                      <div
                        key={day}
                        className={`w-4 h-4 rounded-sm mb-1 cursor-pointer transition-all hover:scale-110 ${
                          intensity > 0.7
                            ? 'bg-blue-600'
                            : intensity > 0.4
                            ? 'bg-blue-400'
                            : intensity > 0.2
                            ? 'bg-blue-200'
                            : 'bg-gray-100'
                        }`}
                        title={`${['周一', '周二', '周三', '周四', '周五', '周六', '周日'][day]} ${hour}:00\n活跃度: ${Math.round(intensity * 100)}%\n用户数: ${count}`}
                      ></div>
                    );
                  })}
                </div>
              ))}
            </div>
            <div className="flex items-center justify-between mt-4 text-sm text-gray-600">
              <span>周一</span>
              <span>周二</span>
              <span>周三</span>
              <span>周四</span>
              <span>周五</span>
              <span>周六</span>
              <span>周日</span>
            </div>
            <div className="flex items-center justify-center mt-4 space-x-2 text-xs text-gray-500">
              <span>低活跃</span>
              <div className="flex space-x-1">
                <div className="w-3 h-3 bg-gray-100 rounded-sm"></div>
                <div className="w-3 h-3 bg-blue-200 rounded-sm"></div>
                <div className="w-3 h-3 bg-blue-400 rounded-sm"></div>
                <div className="w-3 h-3 bg-blue-600 rounded-sm"></div>
              </div>
              <span>高活跃</span>
            </div>
            {/* 热力图统计信息 */}
            <div className="mt-4 p-3 bg-gray-50 rounded-lg">
              <div className="grid grid-cols-3 gap-4 text-sm">
                <div className="text-center">
                  <div className="font-semibold text-lg">
                    {analyticsData?.heatmapData?.reduce((sum, cell) => sum + cell.count, 0) || 
                     Array.from({ length: 168 }, () => Math.floor(Math.random() * 100)).reduce((a, b) => a + b, 0)}
                  </div>
                  <div className="text-gray-600">总活跃次数</div>
                </div>
                <div className="text-center">
                  <div className="font-semibold text-lg">
                    {analyticsData?.heatmapData ? 
                      Math.max(...analyticsData.heatmapData.map(cell => cell.count)) : 
                      Math.floor(Math.random() * 500) + 500}
                  </div>
                  <div className="text-gray-600">峰值活跃度</div>
                </div>
                <div className="text-center">
                  <div className="font-semibold text-lg">
                    {analyticsData?.heatmapData ? 
                      (analyticsData.heatmapData.reduce((sum, cell) => sum + cell.value, 0) / analyticsData.heatmapData.length * 100).toFixed(1) : 
                      (Math.random() * 50 + 25).toFixed(1)}%
                  </div>
                  <div className="text-gray-600">平均活跃度</div>
                </div>
              </div>
            </div>
          </CardContent>
        </Card>
        </TabsContent>

        {/* 报告管理标签页 */}
        <TabsContent value="reports" className="space-y-6">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold">分析报告</h2>
              <p className="text-muted-foreground">管理和生成各类分析报告</p>
            </div>
            <Dialog open={showReportDialog} onOpenChange={setShowReportDialog}>
              <DialogTrigger asChild>
                <Button>
                  <FileText className="w-4 h-4 mr-2" />
                  生成报告
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>生成新报告</DialogTitle>
                  <DialogDescription>
                    选择报告类型并填写相关信息
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="report-name">报告名称</Label>
                    <Input
                      id="report-name"
                      value={newReport.name}
                      onChange={(e) => setNewReport(prev => ({ ...prev, name: e.target.value }))}
                      placeholder="输入报告名称"
                    />
                  </div>
                  <div>
                    <Label htmlFor="report-description">报告描述</Label>
                    <Input
                      id="report-description"
                      value={newReport.description}
                      onChange={(e) => setNewReport(prev => ({ ...prev, description: e.target.value }))}
                      placeholder="输入报告描述"
                    />
                  </div>
                  <div>
                    <Label htmlFor="report-type">报告类型</Label>
                    <Select value={newReport.type} onValueChange={(value) => setNewReport(prev => ({ ...prev, type: value }))}>
                      <SelectTrigger>
                        <SelectValue placeholder="选择报告类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="user">用户分析</SelectItem>
                        <SelectItem value="performance">性能分析</SelectItem>
                        <SelectItem value="business">业务分析</SelectItem>
                        <SelectItem value="custom">自定义</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setShowReportDialog(false)}>
                    取消
                  </Button>
                  <Button onClick={handleGenerateReport} disabled={loading}>
                    {loading ? '生成中...' : '生成报告'}
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>

          <div className="grid gap-4">
            {reports.map((report) => (
              <Card key={report.id}>
                <CardHeader>
                  <div className="flex justify-between items-start">
                    <div>
                      <CardTitle className="flex items-center gap-2">
                        {report.name}
                        {getReportTypeBadge(report.type)}
                      </CardTitle>
                      <CardDescription>{report.description}</CardDescription>
                    </div>
                    <div className="flex items-center gap-2">
                      {getStatusBadge(report.status)}
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => handleExportData('pdf', report.id)}
                        disabled={report.status !== 'completed'}
                      >
                        <Download className="w-4 h-4 mr-2" />
                        下载
                      </Button>
                      <Button 
                        variant="outline" 
                        size="sm"
                        onClick={() => {
                          navigator.clipboard.writeText(`${window.location.origin}/reports/${report.id}`);
                          // 这里可以添加 toast 提示
                        }}
                      >
                        <Share className="w-4 h-4 mr-2" />
                        分享
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="flex items-center justify-between text-sm text-muted-foreground">
                    <span>创建时间: {report.createdAt}</span>
                    <div className="flex items-center gap-4">
                      <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => {
                          // 这里可以导航到报告详情页面
                          console.log('查看报告详情:', report.id);
                        }}
                      >
                        查看详情
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => {
                          setNewReport({
                            name: report.name,
                            description: report.description,
                            type: report.type
                          });
                          setShowReportDialog(true);
                        }}
                      >
                        编辑
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="sm" 
                        className="text-red-600"
                        onClick={() => handleDeleteReport(report.id)}
                      >
                        删除
                      </Button>
                    </div>
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 自定义指标标签页 */}
        <TabsContent value="metrics" className="space-y-6">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold">自定义指标</h2>
              <p className="text-muted-foreground">创建和管理自定义业务指标</p>
            </div>
            <Dialog open={showMetricDialog} onOpenChange={setShowMetricDialog}>
              <DialogTrigger asChild>
                <Button>
                  <Target className="w-4 h-4 mr-2" />
                  添加指标
                </Button>
              </DialogTrigger>
              <DialogContent>
                <DialogHeader>
                  <DialogTitle>添加自定义指标</DialogTitle>
                  <DialogDescription>
                    创建新的业务指标进行监控
                  </DialogDescription>
                </DialogHeader>
                <div className="space-y-4">
                  <div>
                    <Label htmlFor="metric-name">指标名称</Label>
                    <Input
                      id="metric-name"
                      value={newMetric.name}
                      onChange={(e) => setNewMetric(prev => ({ ...prev, name: e.target.value }))}
                      placeholder="输入指标名称"
                    />
                  </div>
                  <div>
                    <Label htmlFor="metric-value">当前值</Label>
                    <Input
                      id="metric-value"
                      type="number"
                      value={newMetric.value}
                      onChange={(e) => setNewMetric(prev => ({ ...prev, value: Number(e.target.value) }))}
                      placeholder="输入当前值"
                    />
                  </div>
                  <div>
                    <Label htmlFor="metric-unit">单位</Label>
                    <Input
                      id="metric-unit"
                      value={newMetric.unit}
                      onChange={(e) => setNewMetric(prev => ({ ...prev, unit: e.target.value }))}
                      placeholder="如: %, ms, 个"
                    />
                  </div>
                  <div>
                    <Label htmlFor="metric-target">目标值</Label>
                    <Input
                      id="metric-target"
                      type="number"
                      value={newMetric.target}
                      onChange={(e) => setNewMetric(prev => ({ ...prev, target: Number(e.target.value) }))}
                      placeholder="输入目标值"
                    />
                  </div>
                </div>
                <DialogFooter>
                  <Button variant="outline" onClick={() => setShowMetricDialog(false)}>
                    取消
                  </Button>
                  <Button onClick={handleAddMetric}>
                    添加指标
                  </Button>
                </DialogFooter>
              </DialogContent>
            </Dialog>
          </div>

          <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
            {customMetrics.map((metric) => (
              <Card key={metric.id}>
                <CardHeader>
                  <div className="flex justify-between items-start">
                    <CardTitle className="text-lg">{metric.name}</CardTitle>
                    <div className="flex items-center gap-1">
                      <Button 
                        variant="ghost" 
                        size="sm"
                        onClick={() => {
                          setNewMetric({
                            name: metric.name,
                            value: metric.value,
                            unit: metric.unit,
                            target: metric.target || 0
                          });
                          setShowMetricDialog(true);
                        }}
                      >
                        <Settings className="w-4 h-4" />
                      </Button>
                      <Button 
                        variant="ghost" 
                        size="sm"
                        className="text-red-600"
                        onClick={() => handleDeleteMetric(metric.id)}
                      >
                        <X className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="space-y-2">
                    <div className="text-3xl font-bold">
                      {metric.value.toFixed(1)}{metric.unit}
                    </div>
                    <div className="flex items-center justify-between">
                      <div className="flex items-center text-sm">
                        {getChangeIcon(metric.change)}
                        <span className={`ml-1 ${
                          metric.change > 0 ? 'text-green-600' : 'text-red-600'
                        }`}>
                          {metric.change > 0 ? '+' : ''}{metric.change.toFixed(1)}
                        </span>
                      </div>
                      {metric.target && (
                        <div className="text-sm text-muted-foreground">
                          目标: {metric.target}{metric.unit}
                        </div>
                      )}
                    </div>
                    {metric.target && (
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div
                          className="bg-blue-600 h-2 rounded-full"
                          style={{ width: `${Math.min((metric.value / metric.target) * 100, 100)}%` }}
                        ></div>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 实时监控标签页 */}
        <TabsContent value="realtime" className="space-y-6">
          <div className="flex justify-between items-center">
            <div>
              <h2 className="text-2xl font-bold">实时监控</h2>
              <p className="text-muted-foreground">实时查看系统状态和用户活动</p>
            </div>
            <div className="flex items-center gap-2">
              <div className="flex items-center gap-2">
                <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                <span className="text-sm text-muted-foreground">实时更新</span>
              </div>
            </div>
          </div>

          <div className="grid gap-6 md:grid-cols-2">
            {/* 实时用户活动 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="w-5 h-5" />
                  实时用户活动
                  <span className="text-sm font-normal text-muted-foreground ml-2">
                    ({analyticsData?.realTimeUsers || 0} 在线)
                  </span>
                </CardTitle>
                <CardDescription>当前在线用户和活动页面</CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {(analyticsData?.realTimeData?.data || realTimeActivityData).map((item, index) => (
                    <div key={index} className="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                      <div className="flex items-center space-x-3">
                        <div className="w-2 h-2 bg-green-500 rounded-full animate-pulse"></div>
                        <div>
                          <p className="font-medium">{item.page}</p>
                          <p className="text-sm text-gray-600">{item.location}</p>
                        </div>
                      </div>
                      <div className="text-right">
                        <p className="font-semibold">{item.users}</p>
                        <p className="text-sm text-gray-600">用户</p>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="mt-4 pt-4 border-t">
                  <div className="flex justify-between text-sm">
                    <span>总在线用户:</span>
                    <span className="font-semibold">{analyticsData?.realTimeUsers || 0}</span>
                  </div>
                  <div className="flex justify-between text-sm">
                    <span>活跃页面:</span>
                    <span className="font-semibold">{(analyticsData?.realTimeData?.data || realTimeActivityData).length}</span>
                  </div>
                </div>
              </CardContent>
            </Card>

            {/* 系统性能监控 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Zap className="w-5 h-5" />
                  系统性能
                  <Button 
                    variant="ghost" 
                    size="sm" 
                    onClick={() => setRealTimeEnabled(!realTimeEnabled)}
                    className="ml-auto"
                  >
                    {realTimeEnabled ? (
                      <><Pause className="w-4 h-4 mr-1" />暂停</>
                    ) : (
                      <><Play className="w-4 h-4 mr-1" />开始</>
                    )}
                  </Button>
                </CardTitle>
                <CardDescription>
                  实时系统资源使用情况 
                  {lastUpdated && (
                    <span className="ml-2 text-xs">
                      最后更新: {lastUpdated.toLocaleTimeString()}
                    </span>
                  )}
                </CardDescription>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  {[
                    { name: 'CPU 使用率', value: Math.floor(Math.random() * 30) + 30, color: 'bg-blue-600' },
                    { name: '内存使用率', value: Math.floor(Math.random() * 20) + 60, color: 'bg-green-600' },
                    { name: '磁盘使用率', value: Math.floor(Math.random() * 15) + 20, color: 'bg-yellow-600' },
                    { name: '网络流量', value: Math.floor(Math.random() * 40) + 40, color: 'bg-purple-600' }
                  ].map((metric, index) => (
                    <div key={index} className="space-y-2">
                      <div className="flex justify-between text-sm">
                        <span>{metric.name}</span>
                        <span className={`font-semibold ${
                          metric.value > 80 ? 'text-red-600' : 
                          metric.value > 60 ? 'text-yellow-600' : 'text-green-600'
                        }`}>
                          {metric.value}%
                          {metric.name === '网络流量' && ' (156 MB/s)'}
                        </span>
                      </div>
                      <div className="w-full bg-gray-200 rounded-full h-2">
                        <div 
                          className={`${metric.color} h-2 rounded-full transition-all duration-500`} 
                          style={{ width: `${metric.value}%` }}
                        ></div>
                      </div>
                    </div>
                  ))}
                </div>
                <div className="mt-4 pt-4 border-t">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="text-muted-foreground">响应时间:</span>
                      <span className="ml-2 font-semibold">{Math.floor(Math.random() * 50) + 20}ms</span>
                    </div>
                    <div>
                      <span className="text-muted-foreground">并发连接:</span>
                      <span className="ml-2 font-semibold">{Math.floor(Math.random() * 500) + 200}</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 页面浏览量实时图表 */}
          <Card>
            <CardHeader>
              <div className="flex justify-between items-center">
                <div>
                  <CardTitle>页面浏览量趋势</CardTitle>
                  <CardDescription>实时页面访问统计</CardDescription>
                </div>
                <div className="flex items-center gap-2">
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => setChartType(chartType === 'bar' ? 'line' : 'bar')}
                  >
                    {chartType === 'bar' ? '折线图' : '柱状图'}
                  </Button>
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={handleRefresh}
                    disabled={refreshing}
                  >
                    {refreshing ? (
                      <Loader2 className="w-4 h-4 animate-spin" />
                    ) : (
                      <RefreshCw className="w-4 h-4" />
                    )}
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="mb-4">
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div className="text-center">
                    <div className="text-2xl font-bold text-blue-600">
                      {(analyticsData?.pageViews || pageViewsData).reduce((sum, item) => sum + item.views, 0)}
                    </div>
                    <div className="text-muted-foreground">总浏览量</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-green-600">
                      {(analyticsData?.pageViews || pageViewsData).length}
                    </div>
                    <div className="text-muted-foreground">活跃页面</div>
                  </div>
                  <div className="text-center">
                    <div className="text-2xl font-bold text-purple-600">
                      {Math.floor((analyticsData?.pageViews || pageViewsData).reduce((sum, item) => sum + item.views, 0) / (analyticsData?.pageViews || pageViewsData).length)}
                    </div>
                    <div className="text-muted-foreground">平均浏览量</div>
                  </div>
                </div>
              </div>
              <ResponsiveContainer width="100%" height={300}>
                {chartType === 'bar' ? (
                  <BarChart data={analyticsData?.pageViews || pageViewsData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="page" />
                    <YAxis />
                    <Tooltip />
                    <Bar dataKey="views" fill="#8B5CF6" name="浏览量" />
                  </BarChart>
                ) : (
                  <LineChart data={analyticsData?.pageViews || pageViewsData}>
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis dataKey="page" />
                    <YAxis />
                    <Tooltip />
                    <Line type="monotone" dataKey="views" stroke="#8B5CF6" strokeWidth={2} name="浏览量" />
                  </LineChart>
                )}
              </ResponsiveContainer>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  );
}